package com.nineshadow.games.util;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Properties;

@Component
@Slf4j
public class UploadFileUtils {

    private ChannelSftp sftp;

    private Session session;

    public void uploadH5(String directory,String fileName, InputStream inputStream){
        openSFTP(ServerEnum.h5.getUsername(),ServerEnum.h5.getPassword(),ServerEnum.h5.getHost());
        try {
            upload(directory,fileName,inputStream);
        } catch (SftpException e) {
            log.error("上传文件出错:{}",e);
        }
        closeConnection();
    }

    public void openSFTP(String username,String password,String host){
        JSch jSch = new JSch();
        try {
            session = jSch.getSession(username, host);
            session.setPassword(password);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking","no");
            session.setConfig(config);
            session.connect();
            sftp = (ChannelSftp)session.openChannel("sftp");
            sftp.connect();
        } catch (JSchException e) {
            log.error("sftp连接错误:{}",e);
        }
    }

    public void upload(String directory,String fileName, InputStream inputStream) throws SftpException {
        try {
            sftp.cd(directory);
            log.info("进入文件目录");
        } catch (SftpException e) {
            sftp.mkdir(directory);
            sftp.cd(directory);
        }
        log.info("开始写入文件...");
        sftp.put(inputStream,fileName);
    }

    public void closeConnection(){
        if (sftp.isConnected()){
            sftp.disconnect();
        }
        if (session.isConnected()){
            session.disconnect();
        }
    }

    enum ServerEnum{
        h5("root","Jiuying_h5_2019","47.103.79.147");
        private String username;
        private String password;
        private String host;

        ServerEnum(String username, String password, String host) {
            this.username = username;
            this.password = password;
            this.host = host;
        }

        public String getUsername() {
            return username;
        }

        public String getPassword() {
            return password;
        }

        public String getHost() {
            return host;
        }
    }
}
